/*
Purpose: Merge permid variable onto tradeline, public record, inquiry, collections, and summary files.  We merge from the header file and use teditseq.  */
  /*We do this because teditseq  is "messed up" (un-mergeable) on the rollup file, so in order to merge tradelines with rollup, we must use permid.*/

libname save "./" ;   

/*header records*/


%macro runme;
data head;
     set save.header&sufx.(keep=teditseq PermID2010);
run;

proc sort data=head;
     by teditseq;
run;

/*trade records*/
proc sort data=save.trade&sufx.;
     by teditseq;
run;

/* merge by teditseq to get permid variable on trade file*/
/* number of unique teditseq on trade file before = number of unique teditseq and permid after merge, that means everyone has a permid, and it's a good merge*/
data save.trade&sufx.(rename=(PermID2010=permid));
     merge head(in=in1) save.trade&sufx.(in=in2);
     by teditseq;
     if in1 and in2;
run;
/*
proc sql;
select count(distinct teditseq) as UniqueTESQ,
       count(distinct permid) as Uniquepermid,
       count(*) as nobs
       from save.trade2007_june;
quit;
run;
endsas;
*/


/*inquiry records*/
proc sort data=save.inquiry&sufx.;
     by teditseq;
run;

/* merge by teditseq to get permid variable on inquiry file*/
data save.inquiry&sufx.(rename=(PermID2010=permid));
     merge head(in=in1) save.inquiry&sufx.(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*public records records*/
proc sort data= save.pubrec&sufx.;
     by teditseq;
run;

/* merge by teditseq to get permid variable on pubrec file*/
data save.pubrec&sufx.(rename=(PermID2010=permid));
     merge head(in=in1) save.pubrec&sufx.(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*collections records*/
proc sort data= save.collect&sufx.;
     by teditseq;
run;

/* merge by teditseq to get permid variable on collections file*/
data save.collect&sufx.(rename=(PermID2010=permid));
     merge head(in=in1) save.collect&sufx.(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*summary records*/
proc sort data= save.summary&sufx.;
     by teditseq;
run;

/* merge by teditseq to get permid variable on summary file*/
data save.summary&sufx.(rename=(PermID2010=permid));
     merge head(in=in1) save.summary&sufx.(in=in2);
     by teditseq;
     if in1 and in2;
run;

proc contents data=save.summary&sufx.;
run;

%mend;

%let sufx = 201006;
%runme;
run;
%let sufx = 201206;
%runme;
run;
%let sufx = 201406;
%runme;
run;
